package com.aiti.lulian.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.BusinessContractImportDto;
import com.aiti.lulian.dto.CardBusinessContractDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CardBusinessContractMapper;
import com.aiti.lulian.service.CardBusinessContractService;
import com.aiti.lulian.service.CardContractCollaboratorService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.ISysDataService;
import com.aiti.lulian.utils.DateFilterUtil;
import com.aiti.lulian.vo.CardBusinessContractVo;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CardBusinessContractServiceImpl extends BaseSerivceImpl<CardBusinessContractMapper, CardBusinessContract> implements CardBusinessContractService {

    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;

    @Autowired
    private ILuLianEnterpriseUserService luLianEnterpriseUserService;

    @Autowired
    private CardContractCollaboratorService cardContractCollaboratorService;

    @Autowired
    private ILuLianEnterpriseUserService luLianService;

    @Autowired
    private ISysDataService sysDataService;



    @Override
    public Message getList(Page page, CardBusinessContractDto dto) {
        String createUserId = dto.getUserId();
        String roleIds = dto.getRoleIds();
        if(StringUtils.isEmpty(roleIds)){
            Message userRoleMessage = cloudShowManagerSubService.getRoleByUserId(createUserId);
            if (userRoleMessage == null) {
                return Message.fail("获取角色信息失败！");
            }
            roleIds = (String)userRoleMessage.getObj();

            if(userRoleMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("查询用户失败");
            }

        }
        if(!StringUtils.isEmpty(roleIds)) {
            String[] split = roleIds.split(StrUtil.COMMA);
            boolean systemAdmin = Arrays.stream(split).filter(f -> "1".equals(f)).count() > 0;
            dto.setSystemAdmin(systemAdmin);
            dto.setUserId(createUserId);
            String dateFilterType = dto.getDateFilterType();
            Date beginDate = dto.getBeginDate();
            Date endDate = dto.getEndDate();
            if(beginDate != null){
                beginDate = DateUtil.beginOfDay(beginDate);
                dto.setBeginDate(beginDate);
            }
            if(endDate != null){
                endDate = DateUtil.endOfDay(endDate);
                dto.setEndDate(endDate);
            }
            if(!StringUtils.isEmpty(dateFilterType)){
                Map<String, DateTime> beginAndEnd = DateFilterUtil.getBeginAndEnd(dateFilterType);
                dto.setBeginDate(beginAndEnd.get("begin"));
                dto.setEndDate(beginAndEnd.get("end"));
            }
            if (!systemAdmin) {
                dto.setEnterpriseAdmin(false);
                Message message = cloudShowManagerSubService.getUserInfo(createUserId);
                if (message == null) {
                    return Message.fail("获取认证企业信息失败！");
                }
                Object obj = message.getObj();
                if (obj == null) {
                    return Message.fail("获取认证企业信息失败！" );
                }
                if (message.getCode() == 1) {
                    return Message.fail("查询用户信息错误");
                }
                ObjectMapper mapper = new ObjectMapper();
                Map resultMap = mapper.convertValue(obj, Map.class);
                //String deptPermission = (String)resultMap.get("deptPermission");
                String deptPermission = "";
                //获取当前用户的权限
                Message userAccessScopeMessage = cloudShowManagerSubService.queryUserAccessScope(createUserId);
                if (userAccessScopeMessage == null) {
                    throw new RuntimeException("获取用户权限失败");
                } else if (! userAccessScopeMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                    throw new RuntimeException("查询用户权限失败");
                } else {
                    deptPermission = (String) userAccessScopeMessage.getObj();
                }
                String deptId = (String)resultMap.get("deptId");
                String enterpriseId = (String)resultMap.get("companyId");
                if(StringUtils.isEmpty(enterpriseId)){
                    //查询当前公司
                    LuLianEnterprise luLianEnterprise = luLianService.selectCurrentUserJoinEnterpriseInfo(dto.getUserId());
                    if(luLianEnterprise != null) {
                        enterpriseId = luLianEnterprise.getBaseId();
                    }else{
                        return Message.fail("获取认证企业信息失败！");
                    }
                }
                dto.setEnterpriseId(enterpriseId);
                dto.setDeptPermission(deptPermission);
                dto.setDeptId(deptId);
                List<String> deptList = new ArrayList();
                if(!StringUtils.isEmpty(deptId)){
                    deptList.add(deptId);
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(deptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            deptList.add(temp);
                        }
                    }

                }
                dto.setDeptList(deptList);
                String filterDeptId = dto.getFilterDeptId();
                List<String> filterDeptList = new ArrayList();
                if(!StringUtils.isEmpty(filterDeptId)){
                    filterDeptList.add(filterDeptId);
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(filterDeptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            filterDeptList.add(temp);
                        }
                    }
                }
                dto.setFilterDeptIdList(filterDeptList);
            }
        }else{
            PageResult rspData = new PageResult(new ArrayList(), new PageInfo(dto.getPageNum(), dto.getPageSize()), page.getTotal());
            return Message.success(rspData);
        }

        List<CardBusinessContractVo> list = this.getBaseMapper().getList(page, dto);
        PageResult rspData = new PageResult(list, new PageInfo(dto.getPageNum(), dto.getPageSize()), page.getTotal());
        return Message.success(rspData);
     }

    @Override
    public Message detailInfo(String baseId) {
        CardBusinessContractVo cardBusinessContractVo = this.getBaseMapper().detailInfo(baseId);
        return Message.success(cardBusinessContractVo);
    }

    @Override
    public Message insertContract(CardBusinessContractDto dto) {
        String createUserId = dto.getBaseCreateBy();
        CardBusinessContract cardBusinessContract = new CardBusinessContract();
        String directorId = dto.getDirectorId();
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", directorId));
        if(enterpriseUser != null){
            String enterpriseId = enterpriseUser.getEnterpriseId();
            dto.setEnterpriseId(enterpriseId);
        }else{
            return Message.fail("获取所选负责人企业信息失败！");
        }

        //查询合同名称是否存在
        List<CardBusinessContract> list = this.list(new LambdaQueryWrapper<CardBusinessContract>().eq(CardBusinessContract::getBaseName, dto.getBaseName()).eq(CardBusinessContract::getEnterpriseId, dto.getEnterpriseId()));
        if(!CollectionUtils.isEmpty(list)){
            return Message.fail("合同名称已存在！");
        }
        BeanUtils.copyProperties(dto, cardBusinessContract);
        cardBusinessContract.setBaseCreateTime(new Date());
        this.save(cardBusinessContract);
        return Message.success();
    }

    @Override
    public Message updateContract(CardBusinessContractDto dto) {
        CardBusinessContract cardBusinessContract = new CardBusinessContract();
        CardBusinessContract oldContract = this.getById(dto.getBaseId());
        if(oldContract == null){
            return Message.fail("合同不存在！");
        }
        String enterpriseId = oldContract.getEnterpriseId();
        //查询合同名称是否存在
        if(StringUtils.isEmpty(dto.getBaseName())){
            return Message.fail("合同名称不能为空！");
        }
        List<CardBusinessContract> list = this.list(new LambdaQueryWrapper<CardBusinessContract>().eq(CardBusinessContract::getBaseName, dto.getBaseName()).eq(CardBusinessContract::getEnterpriseId, dto.getEnterpriseId()).ne(CardBusinessContract::getBaseId, dto.getBaseId()));
        if(!CollectionUtils.isEmpty(list)){
            return Message.fail("合同名称已存在！");
        }
        dto.setBaseUpdateTime(new Date());
        BeanUtils.copyProperties(dto, cardBusinessContract);
        this.updateById(cardBusinessContract);
        return Message.success();
    }

    @Override
    public Message updateListContract(CardBusinessContractDto dto) {
        String field = dto.getField();
        String filedValue = dto.getFieldValue();
        List<String> idList = dto.getIdList();
        if(!StringUtils.isEmpty(field) && !StringUtils.isEmpty(filedValue)){
            UpdateWrapper<CardBusinessContract> wrapper = new UpdateWrapper<>();
            field = StrUtil.toUnderlineCase(field);
            wrapper.set(field, filedValue).in("base_id", idList);
            this.update(wrapper);
        }else{
            return Message.fail("请重新编辑字段！");
        }

        return Message.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message dispatch(CardBusinessContractDto dto) {
        String baseId = dto.getBaseId();
        String[] split = baseId.split(StrUtil.COMMA);

        //删除对应协作人
        LambdaQueryWrapper<CardContractCollaborator> contractCollaboratorWrapper = new LambdaQueryWrapper<>();
        contractCollaboratorWrapper.eq(CardContractCollaborator::getUserId,dto.getDirectorId()).in(CardContractCollaborator::getRelateId, Arrays.asList(split));
        cardContractCollaboratorService.remove(contractCollaboratorWrapper);
        LambdaUpdateWrapper<CardBusinessContract> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(CardBusinessContract::getDirectorId, dto.getDirectorId())
                .set(CardBusinessContract::getDeptId, dto.getDeptId())
                .set(CardBusinessContract::getDirectorName, dto.getDirectorName())
                .set(CardBusinessContract::getDeptName, dto.getDeptName())
                .set(CardBusinessContract::getBaseUpdateTime, new Date())
                .set(CardBusinessContract::getBaseUpdateBy, dto.getUserId())
                .in(CardBusinessContract::getBaseId, Arrays.asList(split));
        this.update(wrapper);
        return Message.success();
    }

    @Override
    public Message importExcel(CardBusinessContractDto dto) {
        MultipartFile file = dto.getFile();
        List<String> errorMessageList = new ArrayList();
        List<BusinessContractImportDto> fileImportList = new ArrayList<>();
        try{
            EasyExcel.read(file.getInputStream(), BusinessContractImportDto.class, new ReadListener<BusinessContractImportDto>(){

                @Override
                public void invoke(BusinessContractImportDto importData, AnalysisContext analysisContext) {

                    fileImportList.add(importData);
                }

                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {

                }
            }).sheet().doRead();
            if(fileImportList.isEmpty()){
                return Message.fail("文件中没有找到数据");
            }else{
                List<BusinessContractImportDto> importList = fileImportList.stream().filter(f->!StringUtils.isEmpty(f.getBaseName())).collect(Collectors.toList());
                if(importList.isEmpty()){
                    return Message.fail("文件中没有找到数据");
                }
                if(importList.size() > 500){
                    return Message.fail("导入数据不能超过500条");
                }
                Message message = cloudShowManagerSubService.getUserInfo(dto.getUserId());
                if (message == null) {
                    return Message.fail("获取用户信息失败！");
                }
                Object obj = message.getObj();
                if (obj == null) {
                    return Message.fail("获取用户信息失败！");
                }
                if (message.getCode() == 1) {
                    return Message.fail("查询用户信息错误");
                }
                ObjectMapper mapper = new ObjectMapper();
                Map resultMap = mapper.convertValue(obj, Map.class);
                String deptId = (String)resultMap.get("deptId");
                String deptName = (String)resultMap.get("deptName");
                String currentRealName = (String)resultMap.get("realname");
                //查询当前公司
                LuLianEnterprise luLianEnterprise = luLianService.selectCurrentUserJoinEnterpriseInfo(dto.getUserId());
                if(luLianEnterprise != null){
                    String enterpriseId = luLianEnterprise.getBaseId();
                    List<String> businessNameList = importList.stream().map(m -> m.getBaseName()).collect(Collectors.toList());
                    List<CardBusinessContract> existList = this.list(new LambdaQueryWrapper<CardBusinessContract>().in(CardBusinessContract::getBaseName, businessNameList).eq(CardBusinessContract::getEnterpriseId, enterpriseId));
                    Map<String, String> businessRecordMap = new HashMap<>();
                    if(!CollectionUtils.isEmpty(existList)){
                        businessRecordMap = existList.stream()
                                .collect(Collectors.toMap(
                                        CardBusinessContract::getBaseName,
                                        CardBusinessContract::getBaseId,
                                        (existing, replacement) -> existing
                                ));
                    }
                    List<SysData> contractStatusList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CONTRACT_STATUS"));
                    Map<String, String> contractStatusMap = contractStatusList.stream().collect(Collectors.toMap(
                            SysData::getBaseName,
                            SysData::getBaseId,
                            (existing, replacement) -> existing
                    ));
                    List<SysData> contractTypeList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CONTRACT_TYPE"));
                    Map<String, String> contractTypeMap = contractTypeList.stream().collect(Collectors.toMap(
                            SysData::getBaseName,
                            SysData::getBaseId,
                            (existing, replacement) -> existing
                    ));

                    List<SysData> paymentMethodList = sysDataService.list(new LambdaQueryWrapper<SysData>().eq(SysData::getDictTypeNo, "CONTRACT_PAYMENT_METHOD"));
                    Map<String, String> paymentMethodMap = paymentMethodList.stream().collect(Collectors.toMap(
                            SysData::getBaseName,
                            SysData::getBaseId,
                            (existing, replacement) -> existing
                    ));

                    List<CardBusinessContract> cntractInfoList = new ArrayList<>();
                    String overrideFlag = dto.getOverrideFlag();
                    for(int i = 0; i <= importList.size()-1; i++){
                        BusinessContractImportDto importData = importList.get(i);
                        CardBusinessContract contractInfo = new CardBusinessContract();
                        if(StringUtils.isEmpty(importData.getBaseName())){
                            errorMessageList.add("第"+(i+1)+"条数据合同名称必填");
                            continue;
                        }

                        if(importData.getTotalPrice() == null){
                            errorMessageList.add("合同名称："+importData.getBaseName()+"对应的数据对应合同总金额必填");
                            continue;
                        }
                        if(importData.getSignDate() == null){
                            errorMessageList.add("合同名称："+importData.getBaseName()+"对应的数据对应签约日期必填");
                            continue;
                        }
                        BeanUtils.copyProperties(importData, contractInfo);
                        contractInfo.setEnterpriseId(enterpriseId);

                        if(businessRecordMap.get(importData.getBaseName()) != null){
                            if("1".equals(overrideFlag)){
                                //覆盖
                                contractInfo.setBaseUpdateTime(new Date());
                                contractInfo.setBaseUpdateBy(dto.getUserId());
                                contractInfo.setDeptId(deptId);
                                contractInfo.setDeptName(deptName);
                                contractInfo.setBaseId(businessRecordMap.get(importData.getBaseName()));
                            }else{
                                //不覆盖
                                errorMessageList.add("合同名称："+importData.getBaseName()+"已存在");
                                continue;
                            }
                        }else{
                            contractInfo.setBaseCreateBy(dto.getUserId());
                            contractInfo.setBaseCreateTime(new Date());
                            contractInfo.setDeptId(deptId);
                            contractInfo.setDeptName(deptName);
                        }
                        contractInfo.setDirectorId(dto.getUserId());
                        contractInfo.setDirectorName(currentRealName);

                        if(contractStatusMap.get(contractInfo.getStatus()) != null){
                            contractInfo.setStatus(contractStatusMap.get(contractInfo.getStatus()));
                        }else{
                            if(!StringUtils.isEmpty(contractInfo.getStatus())){
                                errorMessageList.add("合同名称："+contractInfo.getBaseName()+"合同状态："+contractInfo.getStatus()+"不存在");
                                continue;
                            }

                        }
                        if(contractTypeMap.get(contractInfo.getType()) != null){
                            contractInfo.setType(contractTypeMap.get(contractInfo.getType()));
                        }else{
                            if(!StringUtils.isEmpty(contractInfo.getType())){
                                errorMessageList.add("合同名称："+contractInfo.getBaseName()+"合同类型："+contractInfo.getType()+"不存在");
                                continue;
                            }

                        }
                        if(paymentMethodMap.get(contractInfo.getPaymentMethod()) != null){
                            contractInfo.setPaymentMethod(paymentMethodMap.get(contractInfo.getPaymentMethod()));
                        }else{
                            if(!StringUtils.isEmpty(contractInfo.getPaymentMethod())){
                                errorMessageList.add("合同名称："+contractInfo.getBaseName()+"付款方式："+contractInfo.getPaymentMethod()+"不存在");
                                continue;
                            }

                        }

                        cntractInfoList.add(contractInfo);

                    }
                    if(!CollectionUtils.isEmpty(cntractInfoList)){
                        this.saveOrUpdateBatch(cntractInfoList);
                    }

                }else{
                    return Message.fail("当前用户没有加入公司");
                }

            }
        }catch (Exception e){
            errorMessageList.add(e.getMessage());
        }
        if(!CollectionUtils.isEmpty(errorMessageList)){
            return Message.fail(errorMessageList);
        }else{
            return Message.success();
        }
    }

    @Override
    public List<CardBusinessContractVo> getExportList(CardBusinessContractDto dto) {
        String createUserId = dto.getUserId();
        String roleIds = dto.getRoleIds();
        if(StringUtils.isEmpty(roleIds)){
            Message userRoleMessage = cloudShowManagerSubService.getRoleByUserId(createUserId);
            if (userRoleMessage == null) {
                throw new RuntimeException("获取角色信息失败！");
            }
            roleIds = (String)userRoleMessage.getObj();

            if(userRoleMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                throw new RuntimeException("查询用户失败");
            }

        }
        if(!StringUtils.isEmpty(roleIds)) {
            String[] split = roleIds.split(StrUtil.COMMA);
            boolean systemAdmin = Arrays.stream(split).filter(f -> "1".equals(f)).count() > 0;
            dto.setSystemAdmin(systemAdmin);
            dto.setUserId(createUserId);
            String dateFilterType = dto.getDateFilterType();
            Date beginDate = dto.getBeginDate();
            Date endDate = dto.getEndDate();
            if(beginDate != null){
                beginDate = DateUtil.beginOfDay(beginDate);
                dto.setBeginDate(beginDate);
            }
            if(endDate != null){
                endDate = DateUtil.endOfDay(endDate);
                dto.setEndDate(endDate);
            }
            if(!StringUtils.isEmpty(dateFilterType)){
                Map<String, DateTime> beginAndEnd = DateFilterUtil.getBeginAndEnd(dateFilterType);
                dto.setBeginDate(beginAndEnd.get("begin"));
                dto.setEndDate(beginAndEnd.get("end"));
            }
            if (!systemAdmin) {
                dto.setEnterpriseAdmin(false);
                Message message = cloudShowManagerSubService.getUserInfo(createUserId);
                if (message == null) {
                    throw new RuntimeException("获取认证企业信息失败！");
                }
                Object obj = message.getObj();
                if (obj == null) {
                    throw new RuntimeException("获取认证企业信息失败！");
                }
                if (message.getCode() == 1) {
                    throw new RuntimeException("查询用户信息错误");
                }
                ObjectMapper mapper = new ObjectMapper();
                Map resultMap = mapper.convertValue(obj, Map.class);
                //String deptPermission = (String)resultMap.get("deptPermission");
                String deptPermission = "";
                //获取当前用户的权限
                Message userAccessScopeMessage = cloudShowManagerSubService.queryUserAccessScope(createUserId);
                if (userAccessScopeMessage == null) {
                    throw new RuntimeException("获取用户权限失败");
                } else if (! userAccessScopeMessage.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)) {
                    throw new RuntimeException("查询用户权限失败");
                } else {
                    deptPermission = (String) userAccessScopeMessage.getObj();
                }
                String deptId = (String)resultMap.get("deptId");
                String enterpriseId = (String)resultMap.get("companyId");
                if(StringUtils.isEmpty(enterpriseId)){
                    //查询当前公司
                    LuLianEnterprise luLianEnterprise = luLianService.selectCurrentUserJoinEnterpriseInfo(dto.getUserId());
                    if(luLianEnterprise != null) {
                        enterpriseId = luLianEnterprise.getBaseId();
                    }else{
                        throw new RuntimeException("获取认证企业信息失败！");
                    }
                }
                dto.setEnterpriseId(enterpriseId);
                dto.setDeptPermission(deptPermission);
                dto.setDeptId(deptId);
                List<String> deptList = new ArrayList();
                if(!StringUtils.isEmpty(deptId)){
                    deptList.add(deptId);
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(deptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            deptList.add(temp);
                        }
                    }

                }
                dto.setDeptList(deptList);
                String filterDeptId = dto.getFilterDeptId();
                List<String> filterDeptList = new ArrayList();
                if(!StringUtils.isEmpty(filterDeptId)){
                    filterDeptList.add(filterDeptId);
                    Message deptMessage = cloudShowManagerSubService.getSubDeptByDeptId(filterDeptId);
                    if(deptMessage==null || deptMessage.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
                        throw new RuntimeException("查询子级部门失败");
                    }
                    String deptObj = (String)deptMessage.getObj();
                    if(StringUtils.isNotBlank(deptObj)){
                        String[] deptSplit = deptObj.split(StrUtil.COMMA);
                        for(String temp : deptSplit){
                            filterDeptList.add(temp);
                        }
                    }
                }
                dto.setFilterDeptIdList(filterDeptList);
            }
        }else{
            return new ArrayList();
        }

        List<CardBusinessContractVo> list = this.getBaseMapper().getExportList(dto);
        return list;
    }

    @Override
    public Message insertContractNonCheck(CardBusinessContractDto dto) {
        CardBusinessContract cardBusinessContract = new CardBusinessContract();
        String directorId = dto.getDirectorId();
        LuLianEnterpriseUser enterpriseUser = luLianEnterpriseUserService.getOne(new QueryWrapper<LuLianEnterpriseUser>().eq("user_id", directorId));
        if(enterpriseUser != null){
            String enterpriseId = enterpriseUser.getEnterpriseId();
            dto.setEnterpriseId(enterpriseId);
        }else{
            return Message.fail("获取所选负责人企业信息失败！");
        }

        //查询合同名称是否存在
        String baseName = dto.getBaseName();
        if (StrUtil.isBlank(baseName)) {
            return Message.fail("合同名称不能为空");
        }
        List<CardBusinessContract> list = this.baseMapper.selectListBusiness(dto);
        if (list.size() > 0) {
            //如果名称重复则进行处理
            String existingBaseName = list.get(0).getBaseName();
            String substring = existingBaseName.substring(baseName.length());
            if (StrUtil.isNotBlank(substring)) {
                //如果最后以数字结尾，则将该数字递增后组成新名称
                int sort = Integer.valueOf(substring) + 1;
                baseName = baseName + sort;
            } else {
                //如果最后以汉字结尾，则将数字1添加至末尾组成新名称
                baseName = baseName + 1;
            }
            dto.setBaseName(baseName);
        }
        BeanUtils.copyProperties(dto, cardBusinessContract);
        cardBusinessContract.setBaseCreateTime(new Date());
        this.save(cardBusinessContract);
        return Message.success();
    }
}
